/*
** parser.c for parser in /home/ricard_v//rack/zappy
** 
** Made by vincent ricard
** Login   <ricard_v@epitech.net>
** 
** Started on  Sat Jul  2 14:17:54 2011 vincent ricard
** Last update Sun Jul 10 18:48:31 2011 el-hadji-malick-ndour dieng
*/

#include	<strings.h>
#include	<stdlib.h>
#include	<string.h>
#include	<stdio.h>
#include	<unistd.h>
#include	"parser.h"

char		**args_to_tab(char **args, int nb_args)
{
  char		**tab;
  int		it;
  int		it2;

  it = 0;
  it2 = 1;
  tab = xmalloc(nb_args * sizeof(char **));
  while (it < (nb_args - 1))
    {
      tab[it] = xmalloc(strlen(args[it2]) * sizeof(char *));
      tab[it++] = args[it2++];
    }
  return (tab);
}

int	initiate_team(t_server_params *server, char **names, int pos, int lim)
{
  int		it;
  int		nb_names;

  it = 0;
  nb_names = 0;
  if (server->flag != 0)
    return (pos);
  while ((pos < lim) && (strncmp(names[pos], "-", 1) != 0))
    {
      nb_names++;
      pos++;
    }
   pos -= nb_names;
   server->team = xmalloc((nb_names + 1) * sizeof(char **));
  while (it < nb_names)
    {
      server->team[it] = xmalloc(strlen(names[pos]) * sizeof(char *));
      server->team[it++] = names[pos++];
    }
  server->team[it] = NULL;
  server->flag = 1;
  return (--pos);
}

void		check_params(t_server_params *server)
{
  if (server->port < 1023 || server->port > 65535 )
    aff_error("You port number is either incorrect or does not exist.\
\nPlease choose a port between 1024 and 65534 \n");
  if (server->nb_clients <= 0)
    aff_error("Maximum number of clients allowed by team at the beginning \
of the game must be higher than 0. Please, a different number ( > 0)\n");
  if (server->time < 1 || server->time > 5)
    aff_error("Time speed is either too fast or too slow.\n\
Please choose between 1 and 5 \n");
}

void		parser(t_server_params *server, char **args, int nb_args)
{
  char		**tab;
  int		it;
  int		j;

  j = 1;
  it = 0;
  tab = args_to_tab(args, nb_args);
  while (tab[it] && j < (nb_args - 1))
    {
      if (strcmp(args[j], PORT) == 0)
	  server->port = atoi(args[++j]);
      if (strcmp(args[j], MAP_HEIGHT) == 0)
	server->x = atoi(args[++j]);
      if (strcmp(args[j], MAP_WIDTH) == 0)
	server->y = atoi(args[++j]);
      if (strcmp(args[j], TEAM_NAMES) == 0)
	j = initiate_team(server, args, (++j), nb_args);
      if (strcmp(args[j], NB_CLIENTS) == 0)
	server->nb_clients = atoi(args[++j]);
      if (strcmp(args[j], TIME_SPEED) == 0)
	server->time = atoi(args[++j]);
      it++;
      j++;
    }
  check_params(server);
}

